//
//  JYOauthViewController.swift
//  01.weibo
//
//  Created by 谢玉锋 on 16/7/11.
//  Copyright © 2016年 itheima.cn. All rights reserved.
//

import UIKit
import SVProgressHUD  //用来加载提示的


class JYOauthViewController: UIViewController {

    /// 在loadView里面赋值不用设置view的大小
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = GlobalColor
        
        setupNavigationBar()
        let url = OauthURL()
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
//        JYPrint("\(OauthURL())")
        //添加指示器
        // 添加指示器
//        SVProgressHUD.showErrorWithStatus("你错了", maskType: SVProgressHUDMaskType.Gradient)    // 叉
//        SVProgressHUD.showSuccessWithStatus("你成功了", maskType: SVProgressHUDMaskType.None)     //勾
//        SVProgressHUD.showInfoWithStatus("showInfo", maskType: SVProgressHUDMaskType.None)        // 感叹号 i
        SVProgressHUD.showWithStatus("正在加载登录界面...")       // 进度转,一直存在不消失,除非调用dismiss
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.None)
        
    }

    // 拼接Oauth授权登录界面的url（GET）
    private func OauthURL () ->NSURL {
    let urlString = OauthUrl + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
    return NSURL(string: urlString)!
    }
    
    //设置导航栏
    private func setupNavigationBar () {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("autoFill"))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("close"))
    }
    
    @objc private func autoFill () {
        //document.getElementById('userId').value = '1040681183@qq.com'
        //document.getElementById('passwd').value = 'Johnny1906'
        let js = "document.getElementById('userId').value = '1040681183@qq.com';document.getElementById('passwd').value = 'Johnny1906'"
        webView.stringByEvaluatingJavaScriptFromString(js)
//        print("xxx")
    }
    
    @objc private func close () {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //懒加载 (用var)
    private lazy var webView: UIWebView = UIWebView()

}

//Mark -web 代理方法 (写类外面)
extension JYOauthViewController: UIWebViewDelegate {
    //是否要加载一个请求你
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //获取请求的字符串
        let urlString = request.URL?.absoluteString
//        JYPrint(urlString)
        //判断是否为授权回调地址
        //取消回调 http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330"
        //授权回调 "http://www.baidu.com/?code=57c930f9e3adec1ac98a2b4502c00a8b"
        
        let isredirect_uri = urlString!.hasPrefix(redirect_uri)

        if !isredirect_uri {
        //不是授权地址 (不用拦截)
        return true
            
        }else {
         //要拦截
        let query = request.URL!.query
        let codeString = "code="
            //点击授权按钮
            if query!.hasPrefix(codeString) {
            //获取 code=57c930f9e3adec1ac98a2b4502c00a8b
            let code = (query! as NSString).substringFromIndex(codeString.characters.count)
              
            //获取accessToken (根据 code=57c930f9e3adec1ac98a2b4502c00a8b 获取 accessToken)
            JYUserAccountViewModel.sharaInstance.posdAccessToken(code, loadAccountCallBack: { (error) -> () in
                //授权失败
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("网络不给力!")
                    //如果这个代码写不出来, 先将OC代码写出来,然后再根据OC的对号入座即可
                   dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    self.close()
                   })
                return
                }
                //授权成功
                self.close()
                //跳到欢迎界面
                let controller = JYWelcomViewController()
                (UIApplication.sharedApplication().delegate as! AppDelegate).switchController(controller)
                
            })

            }else {
            //点击取消按钮
            close()
                
            }
            return false
            
        }

    }
    
    //获取accessToken方法
//    private func posdAccessToken (code:String) {
//    
//        let parameters = [
//        "client_id":client_id,
//        "client_secret":client_secret,
//        "grant_type":grant_type,
//        "code":code,
//        "redirect_uri":redirect_uri
//        ]
//    JYNetworkTool.shareInstance.POST(accessTokenURLString, parameters: parameters, progress: nil, success: { (task, responseobject) -> Void in
//        //当授权成功之后,在登录时,不会再来而去直接获取accessToken,除非,取消授权
//        JYPrint("成功: \(responseobject)")
//        //字典转模型
//        let result = responseobject as? [String: AnyObject]
//        //选择绑定                                                                      ???
//        if let dict = result {
//        
//            let userAccount = JYUserAccount(dict: dict)
//            JYPrint(userAccount)
//            
//            //归档
//            //路径
//            let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/account.plist")
//            JYPrint(accountPath)
//            NSKeyedArchiver.archiveRootObject(userAccount, toFile: accountPath)
//        }
//        
//        }) { (task, error) -> Void in
//            
//        JYPrint("失败: \(error)")
//            
//        }
//    
//        
//    }
    
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        if error?.code == 102 {
        return
        }
        // 当设置showErrorWithStatus会将其他的HUDdismiss
        SVProgressHUD.showErrorWithStatus("网络不给力...")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.None)
    }
    
}



